package Base.多线程通信;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈鹏
 */
public class Solve {
    public static void main(String[] args) {
        List<Object> goods = new ArrayList<>();
        long start = System.currentTimeMillis();
        //线程1，来生产商品
        Thread thread1 = new Thread(() -> {
            int num = 0;
            while (System.currentTimeMillis() - start <= 100) {
                //使用goods作为锁对象
                synchronized (goods) {
                    //有商品就让生产者进入等待状态
                    if (goods.size() > 0) {
                        try {
                            goods.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        goods.add("商品" + ++num);
                        System.out.println("生产商品" + num);
                    }
                }
            }

        }, "生产者");
        Thread thread2 = new Thread(() -> {
            int num = 0;
            while (System.currentTimeMillis() - start <= 100) {
                //使用goods作为锁对象
                synchronized (goods) {
//                    商品不足就唤醒生产者生产
                    if (goods.size() <= 0) {
                        goods.notify();
                    } else {
                        goods.remove("商品" + ++num);
                        System.out.println("消费商品" + num);
                    }
                }

            }
        }, "生产者");
//        定义了两个线程，分别是消费者和生产者，同时运行100毫秒，看看供求关系
        thread1.start();
        thread2.start();

    }
}
